package com.example.testapp.activity.fragment;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.study.WeaterMainActivity;
import com.example.testapp.activity.adapter.ListWeatherAdapter;
import com.example.testapp.activity.dabastate.SQLiteCityManager;
import com.example.testapp.activity.model.CityManagerEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by l on 2016/8/2.
 */
public class HomePageFragment extends Fragment {

    public static final String TAG = "HomeContent";
    public static List<CityManagerEntity> mcmb = new ArrayList<>();

    public TextView temp; //温度
    public static TextView currentcity;// 当前城市
    public TextView pm25; //PM值
    public TextView pollution;// 污染程度
    public EditText inputcity;
    public Button searchWeatherBtn;
    public View homeContent;
    private ListView weatherInfolist;

    public static ProgressDialog  Dialog;
    public WeaterMainActivity weaterMainActivity;
    public FragmentAnd mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        weaterMainActivity = (WeaterMainActivity) getActivity();
        mActivity = (FragmentAnd) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        WeaterMainActivity.TAG_H = TAG;
        if(!weaterMainActivity.netErrorFlag){
            homeContent = inflater.inflate(R.layout.include_contetnt_activity, null);
            initView();
            if(WeaterMainActivity.response.getResults() != null){
                setpagedata();
            }
        }else{
           homeContent = inflater.inflate(R.layout.view_main_net_error, null);
        }
        return homeContent;
    }

    private void initView() {
         temp = (TextView)homeContent.findViewById(R.id.temp);
         pm25 = (TextView)homeContent.findViewById(R.id.pm25);
         pollution = (TextView)homeContent.findViewById(R.id.pollution_level);
         currentcity = (TextView)homeContent.findViewById(R.id.currentcity);

        inputcity = (EditText) homeContent.findViewById(R.id.inputcity);
        searchWeatherBtn = (Button) homeContent.findViewById(R.id.btn_search);
        weatherInfolist = (ListView) homeContent.findViewById(R.id.weather_infor_list);
    }

    public void setpagedata() {
         if(Dialog != null){
             Dialog.dismiss();
         }
        autoSetBgPic();
        weatherInfolist.setAdapter(new ListWeatherAdapter(getActivity(), WeaterMainActivity.response.getResults().get(0).getWeather_data()));
        searchWeatherBtn.setOnClickListener(searchWeatherOnClickListener);
        currentcity.setText(WeaterMainActivity.response.getResults().get(0).getCurrentCity());

        if("".equals(WeaterMainActivity.response.getResults().get(0).getPm25())){
            pm25.setText("PM2.5:");
            pollution.setText(R.string.no_data);
            pollution.setBackgroundColor(Color.TRANSPARENT);
        }else{
            pm25.setText("PM2.5：" + WeaterMainActivity.response.getResults().get(0).getPm25());
            int pm = Integer.parseInt(WeaterMainActivity.response.getResults().get(0).getPm25());
            Log.i("TAG", pm + " <-- pm");
            if(pm < 75){
                pollution.setText(R.string.pollution_no);
                pollution.setBackgroundResource(R.mipmap.ic_dl_b);
            }else if(pm > 75 && pm < 100){
                pollution.setText(R.string.pollution_little);
                pollution.setBackgroundResource(R.mipmap.ic_dl_c);
            }else if(pm > 100 && pm < 150){
                pollution.setText(R.string.pollution_mild);
                pollution.setBackgroundResource(R.mipmap.ic_dl_c);
            }else if(pm > 150 && pm < 200){
                pollution.setText(R.string.polltion_moderate);
                pollution.setBackgroundResource(R.mipmap.ic_dl_e);
            }else if(pm > 200){
                pollution.setText(R.string.polltion_severe);
                pollution.setBackgroundResource(R.mipmap.ic_dl_f);
            }
        }

        String todaydata = WeaterMainActivity.response.getResults().get(0).getWeather_data().get(0).getDate();
        String temperature = WeaterMainActivity.response.getResults().get(0).getWeather_data().get(0).getTemperature();
        String subs = null;
        if(todaydata.length() > 14){
            subs = todaydata.substring(14, todaydata.length() - 1);
            temp.setText(subs);
        }else if(temperature.length() > 5){
            String[] str = temperature.split("~ ", 2);
            subs = str[1];
            temp.setText(subs);
        }else{
            temp.setText(temperature);
        }

        // 创建SQLite对象并不会创建数据库
        SQLiteCityManager sqlite = new SQLiteCityManager(getActivity(), "weatherdb", null, 1);
        // 读写数据库
        SQLiteDatabase db = sqlite.getWritableDatabase();
        ContentValues values = new ContentValues(); // ContentValues键值对，类似HashMap
        values.put("cityname", WeaterMainActivity.response.getResults().get(0).getCurrentCity());
        values.put("imageUrl", WeaterMainActivity.response.getResults().get(0).getWeather_data().get(0).getDayPictureUrl());
        values.put("weather", WeaterMainActivity.response.getResults().get(0).getWeather_data().get(0).getWeather());
        values.put("temp", subs);
        Cursor cursor = db.query("coolWeather", null, null, null, null, null, null);
        int i = 0;
        while (cursor.moveToNext()){
            i++;
            Log.i("TAG", i + "==>>i");
            String cityname = cursor.getString(cursor.getColumnIndex("cityname"));
            String weathertext = cursor.getString(cursor.getColumnIndex("weather"));
            cityname = cityname.substring(0, 2);
            String citytext = currentcity.getText().toString().substring(0, 2);
            if(citytext.equals(cityname)){
                if("点击更新".equals(weathertext)){
                    db.update("coolWeather", values, "weather = ?", new String[]{"点击更新"});
                    db.close();
                }
                return;
            }
        }
        db.insert("coolWeather", "cityname", values);
        db.close();
    }

    /**
     * @author htq
     * 根据天气情况自动更换app的皮肤，如晴天则显示晴天的背景，多云则显示多云的背景...
     * 如果当前天气为一种转另外一种天气，则显示前面的那种天气背景，如多云转晴则显示多云的背景
     * 注自动设置背景不会在配置文件中记录设置的是哪张图片背景，仅仅当用户在更换皮肤模块手动更改才
     * 在配置文件中记录
     * bolg:blog.csdn.net/htq__
     */
    private void autoSetBgPic() {
        String path = null;
        String weather = WeaterMainActivity.response.getResults().get(0).getWeather_data().get(0).getWeather();

        if(weather.contains("多云") && !weather.contains("转多云")){
            path="cloudy.jpg";
        }else if(weather.contains("晴") && !weather.contains("转晴")){
            path="fine.jpg";
        }else if(weather.contains("雨")){
            path="rain.jpg";
        }
        if(path != null){
            Intent intent = new Intent("change_background");
            intent.putExtra("path",path);
            intent.putExtra("auto",true);
            getActivity().sendBroadcast(intent);
        }
    }

    public View.OnClickListener searchWeatherOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Dialog = new ProgressDialog(getActivity());
            Dialog.setCancelable(true); // 点击可以取消Dialog的展现
            Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            Dialog.setMessage("正在查询,请稍后...");
            Dialog.show();
            mActivity.senddata(inputcity);
            mActivity.sendcitytext(inputcity.getText().toString());
        }
    };
}
